//
//  DB_TableViewController.m
//  RacMVVM
//
//  Created by 崔博 on 2018/11/28.
//  Copyright © 2018年 崔博. All rights reserved.
//

#import "DB_TableViewController.h"

@interface DB_TableViewController ()
@property (nonatomic, strong) DB_TableViewModel *viewModel;
@end

@implementation DB_TableViewController
- (instancetype)initWithViewModel:(DB_BaseViewModel *)viewModel
{
    if (self == [super initWithViewModel:viewModel]) {
        if ([viewModel shouldRequestRemoteDataOnViewDidLoad]) {
            @weakify(self)
            [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x) {
                @strongify(self)
                [self.viewModel.requestRemoteDataCommand execute:@1];
            }];
        }
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tableView.contentInset = self.contentInset;
    @weakify(self)
    if (self.viewModel.shouldPullToRefresh) {
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh:)];
        self.tableView.mj_header.backgroundColor = [UIColor redColor];
    }
    if (self.viewModel.shouldInfiniteScrolling) {
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            @strongify(self)
            [[[self.viewModel.requestRemoteDataCommand
               execute:@(self.viewModel.page + 1)]
              deliverOnMainThread]
             subscribeNext:^(NSArray *results) {
                 @strongify(self)
                 self.viewModel.page += 1;
                 [self.tableView.mj_footer endRefreshing];
             } error:^(NSError *error) {
                 @strongify(self)
                 [self.tableView.mj_footer endRefreshing];
             } completed:^{
                 @strongify(self)
                 [self.tableView.mj_footer endRefreshing];
             }];
        }];
        self.tableView.mj_footer.backgroundColor = [UIColor greenColor];
    }
    
    RAC(self.tableView.mj_footer, hidden) = [[RACObserve(self.viewModel, dataSource)
                                                    deliverOnMainThread]
                                                   map:^(NSArray *dataSource) {
                                                       @strongify(self)
                                                       NSUInteger count = 0;
                                                       for (NSArray *array in dataSource) {
                                                           count += array.count;
                                                       }
                                                       return @(count >= self.viewModel.perPage);
                                                   }];
    
    
    
}
- (UIEdgeInsets)contentInset
{
    return UIEdgeInsetsMake(88, 0, 0, 0);
}
- (void)refresh:(id)data
{
    @weakify(self)
    [[self.viewModel.requestRemoteDataCommand execute:@1] subscribeNext:^(id x) {
        NSLog(@"%zd",self.viewModel.page);
        self.viewModel.page = 1;
        [self.tableView.mj_footer endRefreshing];
    } completed:^{
        @strongify(self)
        [self.tableView.mj_header endRefreshing];
    }];
}
- (void)dealloc
{
    _tableView.dataSource = nil;
    _tableView.delegate = nil;
}
- (void)reloadData
{
    [self.tableView reloadData];
}

- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath {
    return [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(id)object {}
#pragma mark - tableDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.viewModel.dataSource ? self.viewModel.dataSource.count : 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.viewModel.dataSource[section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
    id object = self.viewModel.dataSource[indexPath.section][indexPath.row];
    [self configureCell:cell atIndexPath:indexPath withObject:(id)object];
       return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section >= self.viewModel.sectionIndexTitles.count) return nil;
    return self.viewModel.sectionIndexTitles[section];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
   
    return self.viewModel.sectionIndexTitles;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.viewModel.didSelectCommand execute:indexPath];
}
#pragma mark - method
-(void)bindViewModel
{
    [super bindViewModel];
    @weakify(self)
    [[[RACObserve(self.viewModel, dataSource)
       distinctUntilChanged]
      deliverOnMainThread]
     subscribeNext:^(id x) {
        @strongify(self)
        [self reloadData];
    }];
}
#pragma mark - lazy
- (UITableView *)tableView
{
    if (!_tableView) {
        CGRect frame = CGRectMake(0, 0, self.view.frame.size.width, 400);
        _tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor lightGrayColor];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
    }
    return _tableView;
}
@end
